import {
  queryOwnersList,
  queryTestingUnitList,
  queryStationList,
  getInsertStationInfo,
  getInsertTestingUnitInfo,
  getInsertOwnersInfo,
  deleteOwnersInfo,
  deleteTestingUnitInfo,
  agcControlList,
  queryStationNameList,
  queryInfo,
  queryStationAuditedFiles,
} from '@/api/dict'
import PinyinMatch from 'pinyin-match'
export default {
  components: {},
  name: 'WindPowerEdit',
  props: {
    detailForm: {
      type: Object,
      default: () => {},
    },
    dispatchLists: {
      //调度
      type: Array,
      default: () => [],
    },
    stationTypeLists: {
      //类型
      type: Array,
      default: () => [],
    },
    voltageLevelLists: {
      //等级
      type: Array,
      default: () => [],
    },
    adjustRegulationLists: {
      //上下调
      type: Array,
      default: () => [],
    },
    queryDetailParam: {
      type: Object,
      default: () => {},
    },
    operate: {
      type: String,
    },
  },
  data() {
    let validForm = (rule, value, callback) => {
      if (!value && this.detailForm.isRegulation == '1') {
        callback(new Error(rule.message))
      } else {
        callback()
      }
    }
    return {
      getInsertStationInfo,
      getInsertTestingUnitInfo,
      getInsertOwnersInfo,
      deleteOwnersInfo,
      deleteTestingUnitInfo,
      ownersList: [], //业主
      queryUnitList: [], //试验单位
      stationList: [], //场站
      agcControlList: [], //协调控制
      queryInputList: [],
      isYes: [
        {
          label: '是',
          value: '1',
        },
        {
          label: '否',
          value: '0',
        },
      ],
      isEnable: [
        {
          label: '启用',
          value: '1',
        },
        {
          label: '退出',
          value: '0',
        },
      ],
      isResponseList: [
        {
          label: '暂未开展惯量响应试验',
          value: '0',
        },
      ],
      formLabelWidth: '150px',
      // 上传
      formDate: new FormData(), //载体
      fileList1: [], //展示的文件列表,
      fileList2: [], //展示的文件列表,
      fileList3: [], //展示的文件列表,
      fileList4: [], //展示的文件列表,
      fileList5: [], //展示的文件列表,
      flagUpload: true,
      stationAuditedFiles: [], //审核通过的文件

      //   校验
      rules: {
        regulationOrgId: [
          {
            required: true,
            message: '请选择所属调管调度机构',
            trigger: 'change',
          },
        ],
        stationName: [
          {
            required: true,
            message: '请输入场站名称',
            trigger: 'change',
          },
        ],
        isProduction: [
          { required: true, message: '请选择', trigger: 'change' },
        ],
        isRegulation: [
          { required: true, message: '请选择', trigger: 'change' },
        ],
        testDate: [{ required: true, message: '请选择', trigger: 'change' }],
        testNumber: [{ required: true, message: '请输入', trigger: 'change' }],
        voltageLevelCode: [
          { required: true, message: '请选择', trigger: 'change' },
        ],
        deadZone: [
          { validator: validForm, message: '请输入死区', trigger: 'change' },
        ],
        adjustRatio: [
          {
            validator: validForm,
            message: '请输入调差系数',
            trigger: 'change',
          },
        ],
        startingPowerThresholdL: [
          {
            validator: validForm,
            message: '请输入启动功率门槛',
            trigger: 'change',
          },
        ],
        lowerLimit: [
          {
            validator: validForm,
            message: '请输入启动下调限幅',
            trigger: 'change',
          },
        ],
        powerAdjustDeviation: [
          {
            validator: validForm,
            message: '请输入功率调节偏差',
            trigger: 'change',
          },
        ],
        upLimit: [
          {
            validator: validForm,
            message: '请输入上调限幅',
            trigger: 'change',
          },
        ],
        startTime: [
          {
            validator: validForm,
            message: '请输入启动时间',
            trigger: 'change',
          },
        ],
        responseTime: [
          {
            validator: validForm,
            message: '请输入响应时间',
            trigger: 'change',
          },
        ],
        adjustTime: [
          {
            validator: validForm,
            message: '请输入调节时间',
            trigger: 'change',
          },
        ],
        onOffFunction: [
          {
            validator: validForm,
            message: '请选择一次调频投退功能',
            trigger: 'change',
          },
        ],
        isUpFunction: [
          {
            validator: validForm,
            message: '请选择一次调频上调功能',
            trigger: 'change',
          },
        ],
        isLowerFunction: [
          {
            validator: validForm,
            message: '请选择一次调频下调功能',
            trigger: 'change',
          },
        ],
        isResponseFunction: [
          {
            validator: validForm,
            message: '请选择惯量响应功能',
            trigger: 'change',
          },
        ],
        agcControl: [
          {
            validator: validForm,
            message: '请输入最大上下调节能力',
            trigger: 'change',
          },
        ],
        maxUpdownPower: [
          {
            validator: validForm,
            message: '请输入每分钟调节速率',
            trigger: 'change',
          },
        ],
        adjustSpeed: [
          {
            validator: validForm,
            message: '请输入每分钟调节速率',
            trigger: 'change',
          },
        ],
        maxUpdownPowerDuration: [
          {
            validator: validForm,
            message: '请输入最大调节能力持续响应时间',
            trigger: 'change',
          },
        ],
      },
    }
  },

  mounted() {
    console.log(this.operate);
    if(this.operate==='add'){
    this.$set(this.detailForm, 'caseIsAudited', '')
    console.log(this.detailForm);
    }
   for(let prop in this.detailForm) {
     console.log(prop + ": " + this.detailForm[prop]);
   }

    queryStationNameList({regulationOrgId: this.detailForm.regulationOrgId}).then((res) => {
      this.queryInputList = res.data
      this.queryInputListCopy = JSON.parse(JSON.stringify(res.data))
      // let stationId = ''
      // if (this.detailForm.stationName) {
      //   stationId = this.queryInputList.filter(
      //     (item) => item.label == this.detailForm.stationName
      //   )[0].value
      // }
      if (this.detailForm.caseIsAudited == 1) {
        this.queryStationAuditedFiles()
      }
    })
  },

  created() {
    this.getAgcControlList()
    this.getQueryTestingUnitList()
    this.getOwnersList()
    this.regulationOrgIdChange()

    // 投入时间的回填
    if (this.detailForm.regulationTime) {
      this.detailForm.regulationTime = this.detailForm.regulationTime.replace(
        'T',
        ' '
      )
    }

    // 文件上传的回显  时间的回显
    // if (this.detailForm.regulationReportForm) {
    //   if (this.detailForm.regulationReportForm.createTime) {
    //     this.detailForm.regulationTime1 =
    //       this.detailForm.regulationReportForm.createTime.replace('T', ' ')
    //   }
    //   this.detailForm.regulationReportForm =
    //     this.detailForm.regulationReportForm.oldName
    // }

    // 新的上传文件的回显
    this.$set(
      this.detailForm,
      'regulationTestPlan',
      this.detailForm.stationFileName
    )
    // this.detailForm.regulationTestPlan =this.detailForm.stationFileName
    if (this.detailForm.uploadTime) {
      this.detailForm.regulationTime2 = this.detailForm.uploadTime.replace(
        'T',
        ' '
      )
    }
    this.$set(this.detailForm, 'caseIsAudited', this.detailForm.isAudited)
    if (this.detailForm.auditedTime) {
      this.detailForm.caseAuditTime = this.detailForm.auditedTime.replace(
        'T',
        ' '
      )
    }

    // if (this.detailForm.regulationTestPlan) {
    //   if (this.detailForm.regulationTestPlan.createTime) {
    //     this.detailForm.regulationTime2 =
    //       this.detailForm.regulationTestPlan.createTime.replace('T', ' ')
    //   }
    //   // this.detailForm.regulationTestPlan =
    //   //   this.detailForm.regulationTestPlan.oldName
    // }
    if (this.detailForm.regulationTestReport) {
      if (this.detailForm.regulationTestReport.createTime) {
        this.detailForm.regulationTime3 =
          this.detailForm.regulationTestReport.createTime.replace('T', ' ')
      }
      this.detailForm.regulationTestReport =
        this.detailForm.regulationTestReport.oldName
    }

    if (this.detailForm.responsePlan) {
      if (this.detailForm.responsePlan.createTime) {
        this.detailForm.regulationTime4 =
          this.detailForm.responsePlan.createTime.replace('T', ' ')
      }
      this.detailForm.responsePlan = this.detailForm.responsePlan.oldName
    }

    if (this.detailForm.responseReport) {
      if (this.detailForm.responseReport.createTime) {
        this.detailForm.regulationTime5 =
          this.detailForm.responseReport.createTime.replace('T', ' ')
      }
      this.detailForm.responseReport = this.detailForm.responseReport.oldName
    }
  },

  computed: {
    disabledSelect() {
      return this.operate == 'edit'
    },
  },

  methods: {
    // 所属调度机构change
    regulationOrgIdChange() {
      queryStationNameList({
        regulationOrgId: this.detailForm.regulationOrgId,
      }).then((res) => {
        this.queryInputList = res.data
        this.queryInputListCopy = JSON.parse(JSON.stringify(res.data))
      })
    },

    //查询审核通过的文件
    queryStationAuditedFiles() {
      let stationId = ''
      if (this.detailForm.stationName) {
        stationId = this.queryInputList.filter(
          (item) => item.label == this.detailForm.stationName
        )[0].value
      }
      queryStationAuditedFiles({
        fileSort: '01',
        stationId: stationId,
        testDate: this.detailForm.testDate,
        testNumber: this.detailForm.testNumber,
      }).then((res) => {
        this.stationAuditedFiles = res.data
        // if (this.stationAuditedFiles && this.stationAuditedFiles.length > 1) {
        //   this.$confirm('该次测试已有审核通过的试验方案，是否替换？', '提示', {
        //     confirmButtonText: '确定',
        //     cancelButtonText: '取消',
        //     type: 'warning',
        //   })
        //   // this.stationAuditedFiles.forEach((item) => {
        //   //   if (item.label === this.detailForm.regulationTestPlan){
        //   //     this.$confirm('该次测试已有审核通过的试验方案，是否替换？', '提示', {
        //   //       confirmButtonText: '确定',
        //   //       cancelButtonText: '取消',
        //   //       type: 'warning',
        //   //     })
        //   //   }
        //   // });
        // }
      })
    },

    async queryInfo() {
      // let val = this.$refs.FuzzyQueryInput.value
      // 获取场站名称的id
      // let stationId = this.$refs.FuzzyQueryInput.queryInputList.filter(item=>item.label==val)[0].value
      let stationId = this.queryInputList.filter(
        (item) => item.label == this.detailForm.stationName
      )[0].value
      // 新增修改的时候根据场站名称回显其他数据
      const res = await queryInfo({ stationId: stationId })
      this.$set(this.detailForm, 'voltageLevelCode', res.data.voltageLevelCode)
      this.$set(this.$refs.owner, 'labels', res.data.ownersName)
      this.$set(this.detailForm, 'isProduction', res.data.isProduction)
      this.$set(this.detailForm, 'stationCap', res.data.stationCap)
      this.$set(this.detailForm, 'productionTime', res.data.productionTime)
    },
    inputChange(val) {
      if (val) {
        this.queryInfo()
      }
    },
    regulationReportFormChange() {
      if (
        !this.detailForm.regulationTestPlan ||
        !this.detailForm.regulationTestReport
      ) {
        this.$message.warning('请先上传一次调频测试方案和一次调频实验报告')
        return false
      } else {
        return true
      }
    },
    handleExceed() {},
    beforeUpload() {},
    isRegulationChange(val) {
      let lists = [
        'deadZone',
        'adjustRatio',
        'startingPowerThreshold',
        'lowerLimit',
        'powerAdjustDeviation',
        'upLimit',
        'startTime',
        'responseTime',
        'adjustTime',
        'companyName',
        'companyId',
        'onOffFunction',
        'isUpFunction',
        'isLowerFunction',
        'isResponseFunction',
        'agcControl',
        'maxUpdownPower',
        'adjustSpeed',
        'maxUpdownPowerDuration',
      ]
      if (val !== '1') {
        for (let k in this.detailForm) {
          lists.forEach((item) => {
            if (k == item) {
              this.detailForm[k] = ''
            }
          })
        }
      }
    },
    uploadFile() {
      //
    },

    onChange1(file, fileList1) {
      // 上传单个文件且能覆盖之前的文件
      if (fileList1.length > 0) {
        this.fileList1 = [fileList1[fileList1.length - 1]] // 获取最后一次选择的文件
      }

      // 获取当前时间
      let dateTime = new Date()
      this.detailForm.regulationTime1 = this.$dayjs(dateTime).format(
        'YYYY-MM-DD HH:mm:ss'
      )

      // 上传文件类型的限制
      let testFile = file.name
        .substring(file.name.lastIndexOf('.') + 1)
        .toLowerCase()
      const extension =
        testFile === 'xlsx' ||
        testFile === 'xls' ||
        testFile === 'pdf' ||
        testFile === 'doc' ||
        testFile === 'docx'
      if (!extension) {
        // this.$message.error('文件上传只能是 pdf/Excel(xlxs、xls) 格式!')
        return false
      } else {
        this.detailForm.regulationReportForm = file.name
        return true
      }
    },

    onChange2(file, fileList2) {
      // 上传单个文件且能覆盖之前的文件
      if (fileList2.length > 0) {
        this.fileList2 = [fileList2[fileList2.length - 1]] // 获取最后一次选择的文件
      }

      // 获取当前时间
      let dateTime = new Date()
      this.detailForm.regulationTime2 = this.$dayjs(dateTime).format(
        'YYYY-MM-DD HH:mm:ss'
      )

      // 切换上传文件的时候,是否审核通过置空
      this.$set(this.detailForm, 'caseIsAudited', '')
      this.$set(this.detailForm, 'caseAuditTime', '')

      // 判断文件类型
      let testFile = file.name
        .substring(file.name.lastIndexOf('.') + 1)
        .toLowerCase()
      const extension =
        testFile === 'xlsx' ||
        testFile === 'xls' ||
        testFile === 'pdf' ||
        testFile === 'doc' ||
        testFile === 'docx'
      if (!extension) {
        this.$message.error('文件上传只能是 pdf/Excel(xlxs、xls)/docx 格式!')
        return false
      } else {
        this.detailForm.regulationTestPlan = file.name
        // 上传一次调频测试方案和一次调频实验报告,才能上传一次调频定值单
        if (
          !this.detailForm.regulationTestPlan ||
          !this.detailForm.regulationTestReport
        ) {
          this.flagUpload = true
        } else {
          this.flagUpload = false
        }
        return true
      }
    },

    onChange3(file, fileList3) {
      // 上传单个文件且能覆盖之前的文件
      if (fileList3.length > 0) {
        this.fileList3 = [fileList3[fileList3.length - 1]] // 获取最后一次选择的文件
      }

      // 获取当前时间
      let dateTime = new Date()
      this.detailForm.regulationTime3 = this.$dayjs(dateTime).format(
        'YYYY-MM-DD HH:mm:ss'
      )

      let testFile = file.name
        .substring(file.name.lastIndexOf('.') + 1)
        .toLowerCase()
      const extension =
        testFile === 'xlsx' ||
        testFile === 'xls' ||
        testFile === 'pdf' ||
        testFile === 'doc' ||
        testFile === 'docx'
      if (!extension) {
        this.$message.error('文件上传只能是 pdf/Excel(xlxs、xls) 格式!')
        return false
      } else {
        this.detailForm.regulationTestReport = file.name
        // 上传一次调频测试方案和一次调频实验报告,才能上传一次调频定值单
        if (
          !this.detailForm.regulationTestReport ||
          !this.detailForm.regulationTestPlan
        ) {
          this.flagUpload = true
        } else {
          this.flagUpload = false
        }
        return true
      }
    },

    onChange4(file, fileList4) {
      // 上传单个文件且能覆盖之前的文件
      if (fileList4.length > 0) {
        this.fileList4 = [fileList4[fileList4.length - 1]] // 获取最后一次选择的文件
      }
      // 获取当前时间
      let dateTime = new Date()
      this.detailForm.regulationTime4 = this.$dayjs(dateTime).format(
        'YYYY-MM-DD HH:mm:ss'
      )

      let testFile = file.name
        .substring(file.name.lastIndexOf('.') + 1)
        .toLowerCase()
      const extension =
        testFile === 'xlsx' ||
        testFile === 'xls' ||
        testFile === 'pdf' ||
        testFile === 'doc' ||
        testFile === 'docx'
      if (!extension) {
        this.$message.error('文件上传只能是 pdf/Excel(xlxs、xls) 格式!')
        return false
      } else {
        this.detailForm.responsePlan = file.name
        return true
      }
    },

    onChange5(file, fileList5) {
      // 上传单个文件且能覆盖之前的文件
      if (fileList5.length > 0) {
        this.fileList5 = [fileList5[fileList5.length - 1]] // 获取最后一次选择的文件
      }

      // 获取当前时间
      let dateTime = new Date()
      this.detailForm.regulationTime5 = this.$dayjs(dateTime).format(
        'YYYY-MM-DD HH:mm:ss'
      )

      let testFile = file.name
        .substring(file.name.lastIndexOf('.') + 1)
        .toLowerCase()
      const extension =
        testFile === 'xlsx' ||
        testFile === 'xls' ||
        testFile === 'pdf' ||
        testFile === 'doc' ||
        testFile === 'docx'
      if (!extension) {
        this.$message.error('文件上传只能是 pdf/Excel(xlxs、xls) 格式!')
        return false
      } else {
        this.detailForm.responseReport = file.name
        return true
      }
    },

    uploadHttpReq(file) {},

    // 文件上传前
    beforeAvatarUpload(file) {
      const isJPG =
        file.type === 'xlsx' || testFile === 'doc' || testFile === 'docx'
      if (!isJPG) {
        this.$message.error('文件上传只能是 Pdf/Excel(xlxs、xls) 格式!')
        return false
      } else {
        return true
      }
    },

    // 获取产权单位字典
    async getOwnersList(val) {
      const res = await queryOwnersList()
      this.ownersList = res.data
      if (val) {
        this.ownersList.forEach((item) => {
          if (item.ownersName == this.$refs.owner.labels)
            this.$refs.owner.labels = item.ownersId
        })
      }
    },
    // 获取试验单位字典
    async getQueryTestingUnitList(val) {
      const res = await queryTestingUnitList()
      this.queryUnitList = res.data
      if (val) {
        this.queryUnitList.forEach((item) => {
          if (item.testingUnitName == this.$refs.testingUnit.labels)
            this.$refs.testingUnit.labels = item.testingUnitId
        })
      }
    },
    // 获取协调控制分类
    async getAgcControlList() {
      const res = await agcControlList()
      this.agcControlList = res.data
    },

    //子组件校验，传递到父组件
    validateForm() {
      let flag = null

      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          flag = true
        } else {
          flag = false
        }
      })
      return flag
    },

    // 试验方案审核时间
    auditChange1(val) {
      // 获取当前时间
      let dateTime = new Date()
      this.detailForm.caseAuditTime = this.$dayjs(dateTime).format(
        'YYYY-MM-DD HH:mm:ss'
      )
      if (val == 1) {
        this.queryStationAuditedFiles()
      }
    },

    // 测试报告审核时间
    auditChange2() {
      // 获取当前时间
      let dateTime = new Date()
      this.detailForm.reportAuditTime = this.$dayjs(dateTime).format(
        'YYYY-MM-DD HH:mm:ss'
      )
    },

    // 过滤方法, 接收一个输入框内容作为参数, 当输入框内容改变后会执行
    PinyinMatchFun(val) {
      if (val) {
        // 定义一个空数组用来存储过滤后的数据
        var result = [] // 开始循环过滤内容
        this.queryInputListCopy.forEach((i) => {
          // 调用 PinyinMatch.match 方法进行拼音与汉字匹配
          var m = PinyinMatch.match(i.label, val)
          if (m) {
            // 匹配成功则push到result数组中
            result.push(i)
          }
        }) // 将过滤后的数组重新赋给下拉列表数据
        this.queryInputList = result
      } else {
        // 如果输入框为空, 则将下拉列表数据还原
        this.queryInputList = this.queryInputListCopy
      }
    },
  },
}
